package com.ihrm.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ihrm.common.exception.RRException;
import com.ihrm.common.utils.PageUtils;
import com.ihrm.common.utils.Query;
import com.ihrm.modules.sys.dao.RoleDao;
import com.ihrm.modules.sys.entity.RoleEntity;
import com.ihrm.modules.sys.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleDao, RoleEntity> implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        if (!params.containsKey("companyId")) {
            throw new RRException("公司不能为空");
        }
        String companyId = (String) params.get("companyId");

        IPage<RoleEntity> page = this.page(
                new Query<RoleEntity>().getPage(params),
                new QueryWrapper<RoleEntity>()
                    .eq("company_id", companyId)
        );

        return new PageUtils(page);
    }

    @Override
    public void assignPerms(Map<String, Object> map) {
        // 清空用户之前分配的角色
        String id = (String) map.get("id");
        // 考虑先查询是否与userId 有在删除
        // 是否有其他优化方案
        roleDao.deletePermsByRoleId(id);
        int i = roleDao.assignPerms(map);
        if (i <= 0) {
            throw new RRException("分配角色失败");
        }
    }

    @Override
    public List<RoleEntity> all(String companyId) {

        return roleDao.selectList(new QueryWrapper<RoleEntity>().eq("company_id", companyId));
    }

}
